define(['jquery', 'bootstrap', 'backend', 'table', 'form','selectpage'], function ($, undefined, Backend, Table, Form, SelectPage) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'package_material_require/index' + location.search,
                    add_url: 'package_material_require/add',
                    edit_url: 'package_material_require/edit',
                    del_url: 'package_material_require/del',
                    multi_url: 'package_material_require/multi',
                    import_url: 'package_material_require/import',
                    table: 'package_material_require',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name'), operate: 'LIKE'},
                        {field: 'paper_tube', title: __('Paper_tube'), operate: 'LIKE'},
                        {field: 'labeling', title: __('Labeling'), operate: 'LIKE'},
                        {field: 'package_bag', title: __('Package_bag'), operate: 'LIKE'},
                        {field: 'card_board', title: __('Card_board'), operate: 'LIKE'},
                        {field: 'carton', title: __('Carton'), operate: 'LIKE'},
                        {field: 'product_label', title: __('Product_label'), operate: 'LIKE'},
                        {field: 'test_report', title: __('Test_report'), operate: 'LIKE'},
                        {field: 'stack_layer', title: __('Stack_layer')},
                        {field: 'product_packaging_quantity_json', title: __('可包装产品数量'), operate: false, formatter: function(value) {
                            try {
                                var data = JSON.parse(value);
                                var result = '';
                                for (var productId in data) {
                                    result += productId + ':' + data[productId] + '<br>';
                                }
                                return result || '无数据';
                            } catch (e) {
                                return value || '无数据';
                            }
                        }},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
            Controller.api.bindProductPackagingEvent();
            // 添加第一行初始数据
            var container = $('#product-packaging-container');
            var firstRow = Controller.api.createProductPackagingRow('', '', 0);
            container.append(firstRow);

            // 初始化第一行的selectpage
            var firstSelectPage = container.find('.product-packaging-row:last-child .selectpage');
            Controller.api.initSelectPage(firstSelectPage, '');
        },
        edit: function () {
            Controller.api.bindevent();
            Controller.api.bindProductPackagingEvent();
            Controller.api.loadExistingProductPackaging();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"), function(data, ret) {
                    // 成功回调
                    return true;
                }, function(data, ret) {
                    // 失败回调
                    return false;
                }, function(form) {
                    // 提交前回调 - 处理产品包装数量JSON
                    var productPackagingObj = {};
                    var hasValidPackaging = false;

                    // 收集所有产品包装数据
                    $('#product-packaging-container .product-packaging-row').each(function(index) {
                        var $row = $(this);
                        var productId = $row.find('input[type="hidden"][name*="[product_id]"]').val();
                        var quantity = $row.find('input[name*="[quantity]"]').val();

                        if (productId && quantity && quantity > 0) {
                            productPackagingObj[productId] = parseFloat(quantity);
                            hasValidPackaging = true;
                        }
                    });

                    if (hasValidPackaging) {
                        // 添加JSON格式的产品包装数据到表单
                        var packagingJson = JSON.stringify(productPackagingObj);
                        $('<input>').attr({
                            type: 'hidden',
                            name: 'row[product_packaging_quantity_json]',
                            value: packagingJson
                        }).appendTo('form[role=form]');
                    }

                    return true;
                });
            },
            createProductPackagingRow: function(productId, quantity, index) {
                return `
                    <div class="row product-packaging-row" style="margin-top: 10px;">
                        <div class="col-xs-12 col-sm-5">
                            <input data-rule="required" data-source="clothmaking_product/getProductInfo" data-field="name" class="form-control selectpage" name="row[product_packaging][${index}][product_id]" type="text" value="${productId}">
                        </div>
                        <div class="col-xs-12 col-sm-5">
                            <input data-rule="required" class="form-control" name="row[product_packaging][${index}][quantity]" type="number" value="${quantity}" min="0" step="0.01">
                        </div>
                        <div class="col-xs-12 col-sm-2">
                            <button type="button" class="btn btn-danger btn-sm remove-product-packaging-btn">
                                <i class="fa fa-minus"></i> 删除
                            </button>
                            <button type="button" class="btn btn-success btn-sm add-product-packaging-btn">
                                <i class="fa fa-plus"></i> 添加
                            </button>
                        </div>
                    </div>
                `;
            },
            // 初始化selectpage的通用函数
            initSelectPage: function(selectPageElement, productId, callback) {
                if (!selectPageElement || selectPageElement.length === 0) {
                    console.warn('SelectPage element not found');
                    return;
                }

                // 使用require方式初始化，确保一致性
                require(['selectpage'], function() {
                    selectPageElement.selectPage({
                        eAjaxSuccess: function(data) {
                            data.list = typeof data.rows !== 'undefined' ? data.rows : (typeof data.list !== 'undefined' ? data.list : []);
                            data.totalRow = typeof data.total !== 'undefined' ? data.total : (typeof data.totalRow !== 'undefined' ? data.totalRow : data.list.length);
                            return data;
                        }
                    });

                    // 如果有产品ID，设置默认值并获取产品名称
                    if (productId && productId !== '') {
                        // 设置默认值
                        selectPageElement.val(productId);

                        // 获取产品名称并显示
                        $.ajax({
                            url: 'clothmaking_product/getProductInfo',
                            type: 'GET',
                            data: {
                                searchKey: 'id',
                                keyValue: productId
                            },
                            async: true,
                            success: function(response) {
                                if (response && response.rows && response.rows.length > 0) {
                                    var productName = response.rows[0].name;
                                    // 设置数据并重新设置值
                                    selectPageElement.selectPageData([{
                                        id: productId,
                                        name: productName
                                    }]);
                                    selectPageElement.val(productId);
                                }
                            },
                            complete: function() {
                                if (callback) {
                                    callback();
                                }
                            }
                        });
                    } else if (callback) {
                        callback();
                    }
                });
            },
            loadExistingProductPackaging: function () {
                // 加载已有的产品包装数据（编辑页面用）
                var packagingText = $('#c-product_packaging_quantity_json').val();
                console.log('原始JSON数据:', packagingText);
                console.log('数据类型:', typeof packagingText);

                if (packagingText && packagingText.trim() !== '') {
                    try {
                        var packagingObj;
                        if (typeof packagingText === 'object') {
                            // 如果已经是对象，直接使用
                            packagingObj = packagingText;
                        } else {
                            // 如果是字符串，尝试解析
                            packagingObj = JSON.parse(packagingText);
                        }
                        console.log('解析后的对象:', packagingObj);
                        $('#product-packaging-container').empty();

                        var index = 0;
                        for (var productId in packagingObj) {
                            if (packagingObj.hasOwnProperty(productId)) {
                                var quantity = packagingObj[productId];

                                // 创建行时设置正确的value，然后初始化selectpage
                                var newRow = Controller.api.createProductPackagingRow(productId, quantity, index);
                                $('#product-packaging-container').append(newRow);

                                // 初始化新行的selectpage组件
                                var newSelectPage = $('#product-packaging-container .product-packaging-row:last-child .selectpage');

                                // 使用通用初始化函数
                                Controller.api.initSelectPage(newSelectPage, productId);

                                index++;
                            }
                        }
                    } catch (e) {
                        console.error('解析产品包装数据失败:', e);
                    }
                }
            },
            bindProductPackagingEvent: function () {

                // 绑定添加产品包装按钮事件
                $(document).on('click', '.add-product-packaging-btn', function () {
                    var container = $('#product-packaging-container');
                    var rowCount = container.find('.product-packaging-row').length;
                    var newRow = Controller.api.createProductPackagingRow('', '', rowCount);
                    container.append(newRow);

                    // 重新初始化新添加的selectpage
                    var newSelectPage = container.find('.product-packaging-row:last-child .selectpage');
                    Controller.api.initSelectPage(newSelectPage, '');
                });

                // 绑定删除产品包装按钮事件
                $(document).on('click', '.remove-product-packaging-btn', function () {
                    $(this).closest('.product-packaging-row').remove();
                });
            }
        }
    };
    return Controller;
});
